import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<EngineerListViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<EngineerListViewState>>{
      EngineerListViewAction.action: _onAction,
      EngineerListViewAction.onGetData: _onGetData,
      EngineerListViewAction.setSort: _setSort,
    },
  );
}

EngineerListViewState _onAction(EngineerListViewState state, Action action) {
  final EngineerListViewState newState = state.clone();
  return newState;
}

EngineerListViewState _onGetData(EngineerListViewState state, Action action) {
  final EngineerListViewState newState = state.clone();
  int page = action.payload['page'];
  List items = action.payload['items'];
  if (page == 1) {
    newState.items = items;
    newState.refreshController.finishRefresh();
  } else {
    List tmp = [];
    tmp.addAll(newState.items);
    tmp.addAll(items);
    newState.items = tmp;
  }
  newState.currentPage = page;
  newState.refreshController.finishLoad(noMore: items.length == 0);
  return newState;
}

EngineerListViewState _setSort(EngineerListViewState state, Action action) {
  final EngineerListViewState newState = state.clone()
    ..currentSortIndex = action.payload
    ..items = null;
  return newState;
}
